package com.hlxl.viewpointrest.controller;

import com.hlxl.viewpointrest.dto.JWTToken;
import com.hlxl.viewpointrest.dto.Login;
import com.hlxl.viewpointrest.service.AuthService;
import com.hlxl.viewpointrest.service.JwtTokenService;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by wyy on 18-5-7
 */
@RestController()
@RequestMapping("/user")
public class UserController {
    private final Log log = LogFactoryUtil.getLog(UserController.class);

    @Autowired
    private AuthService authService;
    @Autowired
    private JwtTokenService jwtTokenService;

    @PostMapping("/login")
    public JWTToken login(@RequestBody Login login, HttpServletResponse response) {
        log.debug("login = " + login);
        try {
            User user = authService.auth(PortalUtil.getDefaultCompanyId(), login.getUsername(), login.getPassword());
            String token = jwtTokenService.createToken(user);//这里不直接使用login里面的username是应为用户有可能使用email登录，后台统一使用screenName做认证。
            response.addHeader("Authorization", "Bearer " + token);
            return new JWTToken().setIdToken(token);
        } catch (Exception e) {
            throw new SecurityException("401");
        }


    }
}
